import { errorAlert, errorModal } from '../modules/system'

export default function errorMiddleware({ dispatch }) {
  return next => action => {
    const { error, payload, ...rest } = action
    const meta = {
      suppressError: false,
      errors: false,
      errorTrigger: 'ALERT',
      ...rest.meta,
    }
    const errors = meta.errors

    // If there's no error or we need to hide the error message then continuing middlware chain
    if (!error) {
      return next(action)
    }

    const {
      status = '',
      statusText = 'An unexpected error occurred.',
    } = payload
    let errorMessage

    // Action creators could define their custom error messages depending on HTTP status in `meta`
    if (typeof payload.formatErrorMessage === 'function') {
      errorMessage = payload.formatErrorMessage(errors)
    } else if (errors && errors[status]) {
      errorMessage = errors[status]
    } else if (typeof payload === 'string') {
      errorMessage = payload
    } else {
      errorMessage = `${status} ${statusText}`.trim()
    }

    const errorAction = meta.errorTrigger === 'ALERT' ? errorAlert : errorModal

    !meta.suppressError && dispatch(errorAction(errorMessage))

    return next({ ...action, errorMessage, meta })
  }
}
